import {createSlice} from "@reduxjs/toolkit"

export const authSlice = createSlice({
  name:'auth',
  initialState:() => {

    //从本地中取登录数据
    const token = localStorage.getItem('token')
    //判断本地中是否有登录数据来返回不同的存储在redux中的登录数据初始值
    if(!token){
      return {
        isLogged:false,
        token:null
      }    
    }else{
      return {
        isLogged:true,
        token,
        }
      } 
    },
  reducers:{
    login(state,action){
      state.isLogged = true;
      state.token = action.payload.token;

      //将登录数据同时存储到本地
      localStorage.setItem('token',state.token)

    },
    logout(state,action){
      state.isLogged = false;
      state.token = null;

      //从本地中删除登录数据
      localStorage.removeItem('token',state.token)
    }
  }
});

export const {login,logout} = authSlice.actions;

export default authSlice.reducer;